#include <ctime>
#include <WinSock2.h>

#include "Player.h"
#include "DataDefine.h"
#include "globalVariables.h"
#include "HitAnimation.h"

Card* getCard(int id);
int copyDeck(list<Card*> src, list<Card*> &dst);

Player::Player(list<Card*> deck, int handcardY, bool isEnemy)
{
	health = INIT_HP;
	currentCost = INIT_COST;
	turnCost = INIT_COST;
	handcardLimit = HANDCARD_LIMIT;
	this->handcardY = handcardY;
	this->isEnemy = isEnemy;
	copyDeck(deck, this->deck);
	handcard.clear();
}

Player::~Player()
{
	for (Handcard* hc : handcard)
	{
		delete hc;
	}
	for (Card* c : graveyard)
	{
		delete c;
	}
	for (Card* c : deck)
	{
		delete c;
	}
}

int Player::draw(int id)
{
	if (id == 0)
	{
		return 0;
	}
	if (deck.size() == 0 && (int)graveyard.size() == 0)
	{
		return 0;
	}
	if (deck.size() == 0)
	{
		for (auto it = graveyard.begin(); it != graveyard.end(); it++)
		{
			deck.push_back(*it);
			graveyard.erase(it);
		}
	}
	for (auto it = deck.begin(); it != deck.end(); it++)
	{
		if ((**it).id == id)
		{
			delete(*it);
			deck.erase(it);
			break;
		}
	}
	if (handcard.size() >= HANDCARD_LIMIT)
	{
		graveyard.push_back(getCard(id));
		return 0;
	}
	handcard.push_back(new Handcard(getCard(id), HANDCARD_X+ (int)handcard.size()*HANDGAP, handcardY));
	return 0;
}

int Player::draw()
{
	if (deck.size() == 0 && graveyard.size() == 0)
	{
		return 0;
	}
	if (deck.size() == 0)
	{
		for (auto it = graveyard.begin(); it != graveyard.end(); it++)
		{
			deck.push_back(*it);
			graveyard.erase(it);
		}
	}
	int index = rand() % deck.size();
	auto it = deck.begin();
	for (int i = 0; i < index; i++)
	{
		it++;
	}
	draw((*it)->id);
	return (*it)->id;
}

int Player::damage(int x)
{
	health -= x;
	//animation
	if (isEnemy)
	{
		animationList.push_back(new HitAnimation(MAP_X + 3 * BLOCK_WIDTH, MAP_Y - (int)(0.5 * BLOCK_HEIGHT)));
	}
	else
	{
		animationList.push_back(new HitAnimation(MAP_X + 3 * BLOCK_WIDTH, MAP_Y + (int)(8.5 * BLOCK_HEIGHT)));
	}
	//death
	if (health <= 0)
	{
		isGameOverChanging = true;
		if (!isSinglePlayer)
		{
			hasTcpLinked = false;
		}
	}
	return 0;
}